<template>
  <div class="comment_wrap">
    <div v-for="(item, index) in commentList" :key="index">
      <div class="comment_item">
        <div class="user_img">
            <img v-if="item.userinfo && item.userinfo.user_img" :src="item.userinfo.user_img" alt="">
            <img v-else src="@/assets/noface.jpg" alt="">
        </div>
        <div class="comment_content">
            <p>
                <span v-if="item.userinfo">{{item.userinfo.name}}</span>
                <span v-else>此用户无姓名</span>
                <span>{{item.comment_date}}</span>
            </p>
            <div>
                {{item.comment_content}}
                <span class="reply" @click="replyClick(item.comment_id)">回复</span>
            </div>
        </div>
      </div>
      <comment-item :commentChild="item.child" @publishItem="replyClick" style="padding-left: 30px" />
    </div>
  </div>
</template>

<script>
import CommentItem from './CommentItem.vue'
export default {
  data () {
    return {
      commentList: null
    }
  },
  created () {
    this.getCommentData()
  },
  methods: {
    // 获取评论数据
    async getCommentData () {
      const res = await this.$http.get('/comment/' + this.$route.params.id)
      // console.log(res)
      if (res.status !== 200) return this.$msg.fail('获取评论数据失败')
      this.commentList = this.changeCommentData(res.data)
      this.$emit('commentLength', res.data.length)
    },
    // 改造评论数组的数据结构
    changeCommentData (arr) {
      function fn (temp) {
        const arr1 = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].parent_id === temp) {
            arr1.push(arr[i])
            arr[i].child = fn(arr[i].comment_id + '')
          }
        }
        return arr1
      }
      return fn(null)
    },
    replyClick (id) {
      this.$emit('replyClick', id)
    }
  },
  components: {
    CommentItem
  }
}
</script>

<style lang="less">
.comment_wrap {
  padding: 10px 10px;
  font-size: 13px;
  >div {
    padding: 7px 0;
    border-bottom: 1px solid #e7e7e7;
  }
  .comment_item {
    padding: 5px 0;
    display: flex;
    .user_img {
        margin-right: 10px;
        img {
            width: 35px;
            height: 35px;
            border-radius: 50%;
        }
    }
    .comment_content {
        flex: 1;
        position: relative;
        p {
            color: #555;
            padding-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }
        .reply {
          color: red;
          position: absolute;
          right: 8px;
        }
    }
  }
}
</style>
